package com.moxie.ocr.ocr.base;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.moxie.ocr.R;
import com.moxie.ocr.ocr.utils.MXConstants;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class MXPermissionDialog extends DialogFragment {
    private MXPermissionManager.PermissionListener permissionListener;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View view = inflater.inflate(R.layout.frag_permission_layout,container);
        requestPersmision();
        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams windowParams = window.getAttributes();
        windowParams.dimAmount = 0.0f;

        window.setAttributes(windowParams);
    }

    protected void requestPersmision() {
        if (isMarshmallow()) {
            if (getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    // Provide an additional rationale to the user if
                    // the permission was not granted
                    // and the user would benefit from additional
                    // context for the use of the permission.
                }
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){

                }
                // Request the permission. The result will be received
                // in onRequestPermissionResult()
                requestPermissions(
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
                        MXConstants.KEY_PERMISSION_REQUEST_SD_CAMERA);
            }else if (!isCameraCanUse()){
                if (permissionListener != null){
                    permissionListener.deniedPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA});
                }
                this.dismiss();
            } else {
                // Permission is already available, start camera preview
                if (permissionListener!=null){
                    permissionListener.allGranted();
                }
                this.dismiss();
            }
        } else {
            if (!isCameraCanUse()){
                if (permissionListener != null){
                    permissionListener.deniedPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA});
                }
            }else{
                if (permissionListener!=null){
                    permissionListener.allGranted();
                }
            }
            this.dismiss();
        }
    }


    private static boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= 23;
    }

    public boolean isCameraCanUse() {
        boolean canUse = true;
        if (Build.MANUFACTURER.equalsIgnoreCase("vivo")){
            Field fieldPassword = null;
            Camera camera = null;
            try {
                camera = Camera.open();
                fieldPassword = camera.getClass().getDeclaredField("mHasPermission");
                fieldPassword.setAccessible(true);
                canUse = (boolean) fieldPassword.get(camera);
            } catch (Exception e) {
                e.printStackTrace();
                canUse = true;
            }finally {
                if (camera!=null){
                    camera.stopPreview();
                    camera.release();
                    camera=null;
                }
            }

        }else{
            Camera mCamera = null;
            try {
                mCamera = Camera.open();
                Camera.Parameters mParameters = mCamera.getParameters();
                mCamera.setParameters(mParameters);
            } catch (Exception e) {
                canUse = false;
            }finally {
                if (mCamera!=null){
                    mCamera.stopPreview();
                    mCamera.release();
                    mCamera=null;
                }
            }
        }
        return canUse;
    }



    /**
     * 请求权限返回
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        boolean allGranted=true;
        ArrayList<String> deniedPermission = new ArrayList<>();

        for (int i=0;i<grantResults.length;i++){
            if (grantResults[i]!=PackageManager.PERMISSION_GRANTED){
                allGranted=false;
                deniedPermission.add(permissions[i]);
            }
        }


        // Request for camera permission.
        if (allGranted) {
            if (permissionListener!=null){
                permissionListener.allGranted();
            }
            // Permission has been granted. Start camera preview Activity.
        } else {
            // Permission request was denied.
            if (permissionListener != null ){
                permissionListener.deniedPermission(deniedPermission.toArray(new String[deniedPermission.size()]));
            }
        }
        this.dismiss();
    }

    public void setListener(MXPermissionManager.PermissionListener permissionListener){
        this.permissionListener = permissionListener;
    }


}
